package message

import (
	"github.com/wzh200x/gateServer/defines"
	hypernexusApp "github.com/wzh200x/hyperNexus/hyperNexusApp"
	hypernexusEntitys "github.com/wzh200x/hyperNexus/hyperNexusEntitys"
	"github.com/wzh200x/hyperNexus/hyperNexusType"
)

type Packet struct {
	hypernexusEntitys.EntityBase
	Size   int32
	Opcode hyperNexusType.TypeOpCode
	Datas  []byte
}

func NewPacket(opcode hyperNexusType.TypeOpCode) *Packet {
	e, _ := hypernexusApp.GHyperNexusApp.GetObjectPoolSystem().GetObject(defines.EnityName_Packet)
	if e == nil {
		e = NewPacketInPool()
	}
	p := e.(*Packet)
	p.InitPacket(opcode)
	return p
}

func (p *Packet) Init() {

}

func (p *Packet) InitPacket(opcode hyperNexusType.TypeOpCode) {
	p.Opcode = opcode
}

func (p *Packet) SetDatas(datas []byte) {
	p.Datas = datas
	p.Size = int32(len(datas))
}

func (p *Packet) GetDatas() []byte {
	return p.Datas
}

func (p *Packet) SetOpCode(opcode hyperNexusType.TypeOpCode) {
	p.Opcode = opcode
}

func (p *Packet) GetOpcode() hyperNexusType.TypeOpCode {
	return p.Opcode
}

func (p *Packet) GetSize() int32 {
	return p.Size
}

// func (this *Packet) EncodeMsg() (error, []byte) {
// 	if this.Msg == nil {
// 		return errors.New("packet is nil"), nil
// 	}
// 	handler := register.GetSocketHandler(this.Opcode)
// 	codecRefType := register.GetCodec(handler.OpCodecType)
// 	codecObj := reflect.New(codecRefType).Interface().(interfaces.ICodec)
// 	msgData, err := codecObj.Encode(this.Msg)
// 	if err != nil {
// 		return err, nil
// 	} else {
// 		return nil, msgData
// 	}
// }

// func (this *Packet) DecodeMsg(msgData []byte) error {
// 	if len(msgData) == 0 {
// 		return nil
// 	}
// 	handler := register.GetSocketHandler(this.Opcode)
// 	codecRefType := register.GetCodec(handler.OpCodecType)
// 	codecObj := reflect.New(codecRefType).Interface().(interfaces.ICodec)
// 	err := codecObj.Decode(msgData, this.Msg)
// 	return err
// }

func (p *Packet) ResetObject() {
	p.EntityBase.Reset()
	p.Size = 0
	p.Opcode = 0
	p.Datas = nil
}

func NewPacketInPool() *Packet {
	e := &Packet{
		EntityBase: hypernexusEntitys.NewEntityBase(defines.EnityName_Packet, defines.EntityType_Packet),
		Size:       0,
		Opcode:     0,
		Datas:      nil,
	}
	return e
}

func PacketObjectCreate() (interface{}, error) {
	return NewPacketInPool(), nil
}

func PacketObjectDestroy(i interface{}) {
}
